package util;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import ar.com.javiproyects.polla.facade.remote.LoteriaFacadeRemote;
import ar.com.javiproyects.polla.facade.remote.PollaFacadeRemote;

public class ServiceLocatorHelper {

	private static InitialContext initialContext;

	/** Creates a new instance of ControllerBeanHelper */
	private ServiceLocatorHelper() {
	}

	private static Object getFacade(Class<?> clz, String name) throws NamingException {
		return getBean("ejb:PollaBack-EAR/PollaBack-EJB//"+ name+ "!" + clz.getName());
	}

	public static LoteriaFacadeRemote getLoteriaFacade() throws NamingException {
		return (LoteriaFacadeRemote) getFacade(LoteriaFacadeRemote.class, "LoteriaFacade");
	}

	public static PollaFacadeRemote getPollaFacade() throws NamingException {
		return (PollaFacadeRemote) getFacade(PollaFacadeRemote.class, "PollaFacade");
	}

	private static Object getBean(String beanName) throws NamingException {
		return getInitialContext().lookup(beanName);
	}

	private static InitialContext getInitialContext() throws NamingException  {
		if (initialContext == null) {
			final Hashtable props = new Hashtable();
			props.put("java.naming.factory.url.pkgs","org.jboss.ejb.client.naming");
			props.put("java.naming.factory.initial","org.jboss.naming.remote.client.InitialContextFactory");
			props.put("java.naming.provider.url","remote://127.0.0.1:4447");
			props.put("jboss.naming.client.ejb.context","true");
			props.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT","false");			
			props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
			
			initialContext = new InitialContext(props);			
		}
		return initialContext;
	}

}
